package com.xm.xm.undercover.service

import android.app.IntentService
import android.content.Intent
import android.util.Log
import com.xm.xm.undercover.R
import com.xm.xm.undercover.utils.ConstValue
import com.xm.xm.undercover.utils.JWebSocketClient
import com.xm.xm.undercover.utils.UserInfo
import kotlinx.android.synthetic.main.activity_room.*
import org.json.JSONObject
import java.net.URI
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.os.IBinder
import org.java_websocket.handshake.ServerHandshake

class SocketIntentService:IntentService("socketIntentService") {



    override fun onHandleIntent(intent: Intent?) {
        // 建立webSocket连接
        val path = "${ConstValue.url}${UserInfo.curUserId}/${UserInfo.curRoom}"
        Log.d("testActivity",path)
        val uri = URI.create(path)

        val client = object : JWebSocketClient(uri) {
            override fun onMessage(message: String) {
                Log.e("JWebSocketClientService", "收到的消息：$message")

                val intent = Intent()
                intent.action = "com.xm.under.SOCKET"
                intent.putExtra("message", message)
                sendBroadcast(intent)
            }

            override fun onOpen(handshakedata: ServerHandshake) {
                super.onOpen(handshakedata)
                Log.e("JWebSocketClientService", "websocket连接成功")
            }
        }
        client.connectBlocking()
        // 发送个人信息，连接服务器
//        val message = GetMessage("7",null,null,"link")
        val message = JSONObject()
        message.put("id","7")
        message.put("mes","link")
        client.send(message.toString())
    }



    override fun onDestroy() {
        super.onDestroy()
    }
}